<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>websocket测试</title>
</head>
<body>

<div>发送消息:</div>
<input type="text" id="msgContent"/>
<input type="button" value="点我发送" onclick="CHAT.chat()"/>

<div>接受消息：</div>
<div id="receiveMsg" style="background-color: gainsboro;"></div>

<script type="application/javascript">

    window.CHAT = {
        socket: null,
        init: function() {
            if (window.WebSocket) {
                CHAT.socket = new WebSocket("ws://localhost:8088/ws"+";langyiquan");
                CHAT.socket.onopen = function() {
                    setInterval(function () {
                        console.log('heart beat~~~');
                        CHAT.socket.send(JSON.stringify({action:2,msg:''}));
                    },10000);
                    console.log("连接建立成功...");
                },
                CHAT.socket.onclose = function() {
                    console.log("连接关闭...");
                },
                CHAT.socket.onerror = function() {
                    console.log("发生错误...");
                },
                CHAT.socket.onmessage = function(e) {
                    console.log("接受到消息：" + e.data);
                    let data = JSON.parse(e.data);
                    var receiveMsg = document.getElementById("receiveMsg");
                    var html = receiveMsg.innerHTML;
                    receiveMsg.innerHTML = html + "<br/>" + data.msg;
                }
            } else {
                alert("浏览器不支持websocket协议...");
            }
        },
        chat: function() {
            let msg = document.getElementById("msgContent").value;
            if (CHAT.socket != null
                && CHAT.socket != undefined
                && CHAT.socket.readyState == WebSocket.OPEN) {
                CHAT.socket.send(JSON.stringify({action:1,msg:msg}));
            }else{
                // 重连websocket
                CHAT.init();
                setTimeout(function () {
                    CHAT.socket.send(JSON.stringify({action:1,msg:msg}));
                },1000);
            }
        }
    };

    CHAT.init();

</script>
</body>
</html>
